package org.geektimes.projects.user.web;


import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;

/**
 * @Author 雪蓑
 * @Date: 2021/3/8 下午10:33
 * @Discription //todo
 */
public class ComponentContext {

    private static final String INIT_CONTEXT = "java:comp/env";
    public static final String CONTEXT_NAME = ComponentContext.class.getName();

    private Context context;

    private static ServletContext servletContext;

    /**
     * 对当前ComponentContext上下文进行初始化，获取到Context ,并且把servletContext上下文注入进去
     */
    public void init(ServletContext servletContext){
        try {
            //先是通过文件路径获取上下文
            context = (Context)new InitialContext().lookup(INIT_CONTEXT);
        } catch (NamingException e) {
           throw new RuntimeException(e);
        }
        servletContext.setAttribute(CONTEXT_NAME,this);
        ComponentContext.servletContext = servletContext;
    }

    /**
     * 获取Bean的公共方法
     * @param jndiName
     * @param <C>
     * @return
     */
    public <C> C getComponent(String jndiName){
        C component = null;
        try {
            component = (C) context.lookup(jndiName);
        } catch (NamingException e) {
            throw new RuntimeException(e);
        }
        return component;
    }

    /**
     * 把当前应用上下文销毁
     */
    public void destroy(){
        if(context != null){
            try {
                context.close();
            } catch (NamingException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 获取ComponentContext 实例
     * @return
     */
    public static ComponentContext getInstance(){
        return (ComponentContext) servletContext.getAttribute(CONTEXT_NAME);
    }
}
